package com.java1234.service.impl;

import cn.hutool.json.JSONUtil;
import com.java1234.entity.R;
import com.java1234.entity.Task;
import com.java1234.service.TasksService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@Slf4j
@Service
public class TasksServiceImpl implements TasksService {
    @Resource
    StringRedisTemplate stringRedisTemplate;


    LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
    String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));


    /**
     * 查询当日全部 tasks
     *
     * @return
     */
    @Override
    public Set<Object> selectTodayTasks(String username) {
        String task_key = "user:" + username + ":"+"task:" + keySuffix;
        ZSetOperations Zset = stringRedisTemplate.opsForZSet();
        Task task = new Task();
        task.setDescription("写一道圆锥曲线求解的初中数学题");
        task.setMin(30);

        // 查询时按score升序获取所有元素（时间顺序）
        Set<Object> tasksByTime = Zset.range(task_key, 0, -1);
        return tasksByTime;
    }

    /**
     * 查询指定id任务
     *
     * @param id
     * @param username
     * @return
     */
    @Override
    public Object selectTaskById(Integer id, String username) {
        String task_key = "user:" + username + ":"+"task:" + keySuffix;
        ZSetOperations Zset = stringRedisTemplate.opsForZSet();
        Object task = Zset.range(task_key, id, id);
        return task;
    }

    /**
     * 新增任务
     *
     * @param task
     * @param username
     * @return
     */
    @Override
    public R insertTask(Task task, String username) {
        String task_key = "user:" + username + ":"+"task:" + keySuffix;
        ZSetOperations Zset = stringRedisTemplate.opsForZSet();
        // 判断是否已经存在
        Double existingScore = Zset.score(task_key, JSONUtil.toJsonStr(task));
        if (existingScore != null) {
            return R.error("该任务已存在");
        }

        // 不存在，则插入新任务
        long currentTimeMillis = System.currentTimeMillis();
        Zset.add(task_key, JSONUtil.toJsonStr(task), currentTimeMillis);

        // 判断今日是否已经创建任务
        Long size = Zset.zCard(task_key);
        if (size == 1) {// 如果是当日第一个任务，则设置当日任务过期时间
            // 当前时间距晚上24:00:00的时间差
            long timeDiff = 24 * 60 * 60 - now.toLocalTime().toSecondOfDay();
            stringRedisTemplate.expire(task_key, timeDiff, TimeUnit.SECONDS);
        }
        return R.ok("任务创建成功");

    }

    /**
     * 更新任务
     *
     * @param task
     * @param id
     * @param username
     * @return
     */
    @Override
    public R updateTask(Task task, Integer id, String username) {
        String task_key = "user:" + username + ":"+"task:" + keySuffix;
        ZSetOperations Zset = stringRedisTemplate.opsForZSet();

        // 判断任务是否存在
        Set<Object> members = Zset.range(task_key, id, id);
        if (members == null || members.isEmpty()) {
            System.out.println(members);
            return R.error("任务不存在");
        }

        // 存在，获取任务
        Object member = members.iterator().next();
        // 获取成员的分数
        Double score = Zset.score(task_key, member);
        Zset.remove(task_key, member);

        // 更新任务
        Zset.add(task_key, JSONUtil.toJsonStr(task), score);
        return R.ok("任务更新成功");

    }

    /**
     * 删除指定任务
     *
     * @param id
     * @param username
     * @return
     */
    @Override
    public R deleteTask(Integer id, String username) {
        String task_key = "user:" + username + ":"+"task:" + keySuffix;
        ZSetOperations Zset = stringRedisTemplate.opsForZSet();
        Set<Object> members = Zset.range(task_key, id, id);
        Object task = members.iterator().next();

        if (task == null) {
            return R.error("任务不存在");
        }

        Zset.remove(task_key, task);
        return R.ok("任务删除成功");
    }

    @Override
    public R updateTaskStatus(Integer status, Integer id, String username) {
        String task_key = "user:" + username + ":"+"task:" + keySuffix;
        ZSetOperations Zset = stringRedisTemplate.opsForZSet();

        // 判断任务是否存在
        Set<Object> members = Zset.range(task_key, id, id);
        if (members == null || members.isEmpty()) {
            System.out.println(members);
            return R.error("任务不存在");
        }

        // 存在，获取任务
        Object member = members.iterator().next();
        // 获取成员的分数
        Double score = Zset.score(task_key, member);
        Zset.remove(task_key, member);

        // 更新任务状态
        Task task = JSONUtil.toBean(JSONUtil.toJsonStr(member), Task.class);
        task.setStatus(status);

        // 更新任务
        Zset.add(task_key, JSONUtil.toJsonStr(task), score);
        return R.ok(task.getStatus());
    }


}
